//
//  SWALPhotosCollectionViewController.swift
//  ChildStory
//
//  Created by linhan on 2017/1/6.
//  Copyright © 2017年 Aiya. All rights reserved.
//

import Foundation
import UIKit

//MARK ============================================================================================
//==============================              图片列表页              ===============================
//=================================================================================================

protocol SWALPhotosCollectionViewControllerDelegate:NSObjectProtocol
{
    func photosCollectionViewController(_ viewController: SWALPhotosCollectionViewController, didFinishChooseWithPhotos photos: [SWALPhoto])
    func photosCollectionViewControllerDidCancel(_ viewController: SWALPhotosCollectionViewController)
}

class SWALPhotosCollectionViewController: SWBaseViewController,UICollectionViewDataSource,UICollectionViewDelegate,CollectionViewCellDelegate,SWAssetsLibraryHelperDelegate
{
    weak var delegate:SWALPhotosCollectionViewControllerDelegate?
    var allowsMultipleSelection:Bool = false
    var maxCount:Int = 1
    var cancelCallback:(()->Void)?
    var chooseCallback:(([SWALPhoto])->Void)?
    weak var album:SWALAlbum?
    
    private var _count:Int = 0{
        didSet{
            _completionBtn.isEnabled = _count > 0
            let title:String = _count > 0 ? "完成(\(_count))" : "完成"
            _completionBtn.setTitle(title, for: .normal)
            _completionBtn.setTitle(title, for: .disabled)
        }
    }
    
    private var _photos:[SWALPhoto] = []
    private var _photo:UIImage?
    //多选时的图片容器
    private var _selectedPhotos:Set<SWALPhoto> = Set<SWALPhoto>()
    
    lazy private var _bottomToolbar:UIView = UIView()
    
    lazy private var _noPhotoTipLabel:UILabel = UILabel()
    lazy private var _completionBtn:UIButton = UIButton(type:.custom)
    
    private var _collectionView:UICollectionView?
    private weak var _previewViewController:SWPickerPreivewViewController?
    
    init(photos:[SWALPhoto])
    {
        super.init(nibName: nil, bundle: nil)
        _photos = photos
        let indexs:[Int] = photos.map({$0.index})
        print("indexs:", indexs)
    }
    
    init(album:SWALAlbum)
    {
        super.init(nibName: nil, bundle: nil)
        self.album = album
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit
    {
        print("DEINIT SWPhotosCollectionViewController")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }
    
    //关闭
    func close()
    {
        dismiss(animated: true, completion: nil)
    }
    
    private func setup()
    {
        createNavigationRightButton("取消", target: self, action: #selector(closeBtnTapped))
        
        let bottomToolbarHeight:CGFloat = 40
        
        var numOfHorizontal:Int = 4
        if SWDevice.size > .iPhone47inch{
            numOfHorizontal = 5
        }
        
        let Grid:CGFloat = 4
        let cellWidth:CGFloat = (self.view.width - (CGFloat(numOfHorizontal + 1) * Grid)) / CGFloat(numOfHorizontal)
        let layout:UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.itemSize = CGSizeMake(cellWidth, cellWidth)
        //横向最小间隔
        layout.minimumInteritemSpacing = Grid
        //纵向最小间隔
        layout.minimumLineSpacing = Grid
        layout.sectionInset = UIEdgeInsetsMake(Grid, Grid, Grid, Grid)
        
        var collectionViewFrame = view.bounds
        if allowsMultipleSelection
        {
            collectionViewFrame = CGRectMake(0, 0, view.width, view.height - bottomToolbarHeight)
        }
        _collectionView = UICollectionView(frame: collectionViewFrame, collectionViewLayout: layout)
        _collectionView?.backgroundColor = UIColor.white
        _collectionView?.register(SWAssetCollectionCell.self, forCellWithReuseIdentifier: "SWAssetCollectionCell")
        _collectionView?.dataSource = self
        _collectionView?.delegate = self
        _collectionView?.isHidden = true
        view.addSubview(_collectionView!)
        
        
        if allowsMultipleSelection
        {
            createBottomToolbar(y: view.height - bottomToolbarHeight, height: bottomToolbarHeight)
        }
        
        let WarningTextFont:UIFont = SWAppearanceManager.themeStyle.fontOfSize(15)
        _noPhotoTipLabel = UILabel.labelWithLimitWidth(view.frame.width - 20, text: "相册中没有任何照片", font: WarningTextFont)
        _noPhotoTipLabel.isHidden = true
        _noPhotoTipLabel.textColor = UIColor.darkGray
        _noPhotoTipLabel.textAlignment = .center
        view.addSubview(_noPhotoTipLabel)
        _noPhotoTipLabel.snp_makeConstraints({make in
            make.center.equalTo(view)
        })
        
        
        
        if let album = album
        {
            SWAssetsLibraryHelper.shared().addDelegate(self)
            SWAssetsLibraryHelper.shared().fetchPhotoList(album: album)
        }
        else
        {
            _collectionView?.isHidden = !(_photos.count > 0)
        }
    }
    
    private func createBottomToolbar(y:CGFloat, height:CGFloat)
    {
        _bottomToolbar.frame = CGRectMake(0, y, view.width, height)
        _bottomToolbar.backgroundColor = UIColor.white
        view.addSubview(_bottomToolbar)
        
        let line:UIView = UIView()
        line.backgroundColor = UIColor(hex: 0xc8c8c8)
        line.frame = CGRectMake(0, 0, view.width, 1)
        _bottomToolbar.addSubview(line)
        
        _completionBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        _completionBtn.titleLabel?.textAlignment = .right
        _completionBtn.setTitle("完成(99)", for: .normal)
        _completionBtn.setTitleColor(UIColor(hex: 0x908f8f), for: .normal)
        _completionBtn.sizeToFit()
        _completionBtn.center = CGPointMake(_bottomToolbar.width - _completionBtn.width * 0.5 - 15, _bottomToolbar.height * 0.5)
        _completionBtn.addTarget(self, action: #selector(completionBtnTapped), for: .touchUpInside)
        _bottomToolbar.addSubview(_completionBtn)
        
        _count = 0
    }
    
    //相册空
    func albumFetchEmpty()
    {
        _noPhotoTipLabel.isHidden = false
    }
    
    //相片获取
    func photosFetchComplete(_ photos:[SWALPhoto])
    {
        _photos = photos
        _collectionView?.isHidden = false
        _collectionView?.reloadData()
        _collectionView?.alpha = 0
        UIView.animate(withDuration:0.2, animations: {
            self._collectionView?.alpha = 1
        })
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    {
        return _photos.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
    {
        let cell:SWAssetCollectionCell = collectionView.dequeueReusableCell(withReuseIdentifier: "SWAssetCollectionCell", for: indexPath) as! SWAssetCollectionCell
        cell.delegate = self
        let index:Int = indexPath.row
        if let photo = _photos.valueAt(index)
        {
            cell.photo = photo
            photo.fetchThumbnail()
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
    {
        let index:Int = indexPath.row
        if allowsMultipleSelection
        {
            let previewViewController = SWPickerPreivewViewController(photos: _photos, selectedCount:_selectedPhotos.count, index: index)
            previewViewController.selecteCallback = {[weak self] photo in
                self?.selectPhoto(photo)
            }
            previewViewController.deselecteCallback = {[weak self] photo in
                self?.deselectPhoto(photo)
            }
            previewViewController.chooseCallback = {[weak self] photos in
                self?.completeChoose()
            }
            _previewViewController = previewViewController
            navigationController?.pushViewController(previewViewController, animated: true)
        }
        else
        {
            if let photo = _photos.valueAt(index)
            {
                //chooseCallback?([photo])
                delegate?.photosCollectionViewController(self, didFinishChooseWithPhotos: [photo])
            }
        }
    }
    
    func collectionViewCell(_ cell:UICollectionViewCell, click action:String, argument aArgument:[AnyHashable:Any]?)
    {
        if action == CallbackAction.Select
        {
            if let photo = (cell as? SWAssetCollectionCell)?.photo
            {
                selectPhoto(photo)
            }
        }
        else if action == CallbackAction.Deselect
        {
            if let photo = (cell as? SWAssetCollectionCell)?.photo
            {
                deselectPhoto(photo)
            }
        }
    }
    
    //照片选中
    private func selectPhoto(_ photo:SWALPhoto)
    {
        //选择数量不能超过一定数量
        if _selectedPhotos.count >= maxCount && maxCount > 0
        {
            SVProgressHUD.showError(withStatus: "选择的照片不能超过\(maxCount)张")
            return
        }
        photo.selected = true
        _selectedPhotos.insert(photo)
        photoSelectChanged(photo)
        _previewViewController?.selectPhoto(photo)
    }
    
    //取消选中
    private func deselectPhoto(_ photo:SWALPhoto)
    {
        photo.selected = false
        _selectedPhotos.remove(photo)
        photoSelectChanged(photo)
        _previewViewController?.deselectPhoto(photo)
    }
    
    //照片选中/取消选中
    private func photoSelectChanged(_ photo:SWALPhoto)
    {
        if let index = _photos.index(where: {photo.id == $0.id})
        {
            _count = _selectedPhotos.count
            _previewViewController?.photoSelectCountChanged(_count)
            _collectionView?.reloadItems(at: [IndexPath(row: index, section: 0)])
        }
    }
    
    private func completeChoose()
    {
        var photos:[SWALPhoto] = _selectedPhotos.map({$0})
        photos.sort{$0.index < $1.index}
        //chooseCallback?(photos)
        delegate?.photosCollectionViewController(self, didFinishChooseWithPhotos: photos)
    }
    
    //MARK ============================================================================================
    //==============================               Selector             ===============================
    //=================================================================================================
    
    
    @objc private func closeBtnTapped()
    {
        //cancelCallback?()
        //close()
        delegate?.photosCollectionViewControllerDidCancel(self)
    }
    
    @objc private func completionBtnTapped()
    {
        completeChoose()
    }
    
}


//MARK ============================================================================================
//==============================            图片预览列表页            ===============================
//=================================================================================================

fileprivate class SWPickerPreivewViewController: SWBaseViewController,SWPhotoViewerDelegate
{
    var selecteCallback:((SWALPhoto)->Void)?
    var deselecteCallback:((SWALPhoto)->Void)?
    var chooseCallback:(([SWALPhoto])->Void)?
    
    private var _photos:[SWLocalPVPhoto]
    private var _index:Int = 0
    
    private var _photoViewer:SWPhotoViewer?
    private var _selectedBtn:UIButton = UIButton(type: .custom)
    private var _topBar:UIView = UIView()
    private var _bottomBar:UIView = UIView()
    lazy private var _completionBtn:UIButton = UIButton(type:.system)
    
    override var prefersNavigationBarHidden: Bool{
        return true
    }
    
    private var _toolbarHidden:Bool = false{
        didSet{
            if _toolbarHidden != oldValue
            {
                
            }
        }
    }
    
    private var _selectedCount:Int = 0
    
    deinit
    {
        print("DEINIT SWPickerPreivewViewController")
    }
    
    init(photos:[SWALPhoto], selectedCount:Int, index:Int = 0)
    {
        _photos = photos.map({SWLocalPVPhoto(photo: $0)})
        _selectedCount = selectedCount
        _index = index
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }
    
    private func setup()
    {
        automaticallyAdjustsScrollViewInsets = false
        view.backgroundColor = UIColor.black
        
        let photoViewer:SWPhotoViewer = SWPhotoViewer(frame: view.frame)
        photoViewer.registerClassForPhotoFetcher(SWPhotoViewerAssetFetcher.self)
        photoViewer.delegate = self
        photoViewer.reloadData()
        photoViewer.showFromIndex(_index, rect: nil)
        view.addSubview(photoViewer)
        _photoViewer = photoViewer
        
        let topBar:UIView = UIView()
        topBar.backgroundColor = UIColor(white: 0, alpha: 0.5)
        topBar.frame = CGRectMake(0, 0, view.width, 64)
        view.addSubview(topBar)
        _topBar = topBar
        
        _selectedBtn.setBackgroundImage(UIImage(named:"child_radio_normal"), for: .normal)
        _selectedBtn.setBackgroundImage(UIImage(named:"child_radio_selected"), for: .selected)
        _selectedBtn.sizeToFit()
        _selectedBtn.frame = CGRectMake(topBar.width - _selectedBtn.width - 20, 20, _selectedBtn.width, _selectedBtn.height)
        _selectedBtn.addTarget(self, action: #selector(selectedBtnTapped), for: .touchUpInside)
        topBar.addSubview(_selectedBtn)
        
        let backBtn:UIButton = UIButton(type: .custom)
        backBtn.setImage(UIImage(named:"global_btn_back"), for: .normal)
        backBtn.sizeToTouchEasy()
        backBtn.center = CGPointMake(15, 44)
        backBtn.addTarget(self, action: #selector(backBtnTapped), for: .touchUpInside)
        topBar.addSubview(backBtn)
        
        
        
        let bottomBarHeight:CGFloat = 40
        let bottomBar:UIView = UIView()
        bottomBar.backgroundColor = UIColor(white: 0, alpha: 0.5)
        bottomBar.frame = CGRectMake(0, view.height - bottomBarHeight, view.width, bottomBarHeight)
        view.addSubview(bottomBar)
        _bottomBar = bottomBar
        
        _completionBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        _completionBtn.titleLabel?.textAlignment = .right
        _completionBtn.setTitle("完成(99)", for: .normal)
        _completionBtn.setTitleColor(UIColor(hex: 0x908f8f), for: .normal)
        _completionBtn.sizeToFit()
        _completionBtn.center = CGPointMake(bottomBar.width - _completionBtn.width * 0.5 - 15, bottomBar.height * 0.5)
        _completionBtn.addTarget(self, action: #selector(completionBtnTapped), for: .touchUpInside)
        _bottomBar.addSubview(_completionBtn)
        
        if let photo = _photos.valueAt(_index)?.photo
        {
            _selectedBtn.isSelected = photo.selected
        }
        photoSelectCountChanged(_selectedCount)
    }
    
    //照片选中
    func selectPhoto(_ photo:SWALPhoto)
    {
        _selectedBtn.isSelected = true
    }
    
    //取消选中
    func deselectPhoto(_ photo:SWALPhoto)
    {
        _selectedBtn.isSelected = false
    }
    
    //照片选中/取消选中
    func photoSelectCountChanged(_ count:Int)
    {
        _selectedCount = count
        _completionBtn.isEnabled = count > 0
        let title:String = count > 0 ? "完成(\(count))" : "完成"
        _completionBtn.setTitle(title, for: .normal)
        _completionBtn.setTitle(title, for: .disabled)
    }
    
    
    //MARK ============================================================================================
    //==============================        SWPhotoViewerDelegate       ===============================
    //=================================================================================================
    
    //照片总数
    func numberOfPhotosInPhotoViewer(_ photoViewer: SWPhotoViewer) -> Int
    {
        return _photos.count
    }
    
    //对应位置的照片
    func photoViewer(_ photoViewer: SWPhotoViewer, photoAtIndex index: Int) -> SWPVPhoto?
    {
        return _photos.valueAt(index)
    }
    
    func photoViewer(_ photoViewer: SWPhotoViewer, didSingleTapAtIndex index: Int)
    {
        _toolbarHidden = !_toolbarHidden
    }
    
    func photoViewer(_ photoViewer: SWPhotoViewer, didScrollToIndex index: Int)
    {
        _index = index
        if let photo = _photos.valueAt(_index)?.photo
        {
            _selectedBtn.isSelected = photo.selected
        }
    }
    
    
    @objc private func selectedBtnTapped()
    {
        if let photo = _photos.valueAt(_index)?.photo
        {
            if _selectedBtn.isSelected
            {
                deselecteCallback?(photo)
            }
            else
            {
                selecteCallback?(photo)
            }
        }
    }
    
    @objc private func backBtnTapped()
    {
        navigationController?.popViewController(animated: true)
    }
    
    @objc private func completionBtnTapped()
    {
        chooseCallback?([])
    }
    
    
}
